package web.bean;


import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.util.ArrayList;
import java.util.List;

@ManagedBean
@SessionScoped
public class LocaleBean {
    private static final String LANG_COOKIE_KEY = "mini_blog_lang_cookie";
    private static final String DEFAULT_LANG = "ro";

    private String currentLanguage;

    @PostConstruct
    public void init() {
        String cookieLang = BeanUtils.getCookieValue(LANG_COOKIE_KEY);
        if (cookieLang == null) {
            cookieLang = DEFAULT_LANG;
        }
        currentLanguage = cookieLang;
    }

    public String getCurrentLanguage() {
        return currentLanguage;
    }

    public void setCurrentLanguage(String currentLanguage) {
        this.currentLanguage = currentLanguage;
        BeanUtils.setCookie(LANG_COOKIE_KEY, currentLanguage);
    }

    public List<String> getAllLanguages() {
        return Languages.getLanguages();
    }

    public void changeLanguage() {
        setCurrentLanguage(Languages.getNextLanguage(currentLanguage));
    }
}

class Languages {
    private static List<String> languages = new ArrayList<String>() {{
        add("ro");
        add("en");
    }};

    /**
     * Gets the next language from the supported languages list
     *
     * @param currentLanguage the current language
     * @return the next language in circular rotation (i.e. ro -> en -> hu -> ro -> ...)
     */
    public static String getNextLanguage(String currentLanguage) {
        int currentLangIndex = languages.indexOf(currentLanguage);

        if (currentLangIndex < (languages.size() - 1)) {
            return languages.get(currentLangIndex + 1);
        } else {
            return languages.get(0);
        }
    }

    public static List<String> getLanguages() {
        return languages;
    }

}
